/*
 * @Author: 李无敌
 * @Date: 2025-01-27 10:00:00
 * @LastEditors: 李无敌
 * @LastEditTime: 2025-01-27 10:00:00
 * @FilePath: \nest-base\src\common\plugins\csp-report.plugin.ts
 * @Description: CSP违规报告Fastify插件
 */

import { FastifyPluginAsync } from 'fastify';
import { CSPReportMiddleware, CSPViolationReport } from '../middleware/csp-report.middleware';

export const cspReportPlugin: FastifyPluginAsync = async (fastify) => {
  const cspReportMiddleware = new CSPReportMiddleware();

  // 注册CSP违规报告路由
  fastify.post('/csp-report', {
    schema: {
      description: 'CSP违规报告端点',
      tags: ['security'],
      body: {
        type: 'object',
        properties: {
          'csp-report': {
            type: 'object',
            properties: {
              'document-uri': { type: 'string' },
              'referrer': { type: 'string' },
              'violated-directive': { type: 'string' },
              'original-policy': { type: 'string' },
              'blocked-uri': { type: 'string' },
              'source-file': { type: 'string' },
              'line-number': { type: 'number' },
              'column-number': { type: 'number' },
              'status-code': { type: 'number' }
            },
            required: ['document-uri', 'violated-directive', 'original-policy', 'blocked-uri']
          }
        },
        required: ['csp-report']
      },
      response: {
        204: {
          description: '报告接收成功',
          type: 'null'
        },
        400: {
          description: '无效的报告格式',
          type: 'object',
          properties: {
            error: { type: 'string' }
          }
        },
        500: {
          description: '服务器内部错误',
          type: 'object',
          properties: {
            error: { type: 'string' }
          }
        }
      }
    }
  }, async (request, reply) => {
    return cspReportMiddleware.handleCSPReport(request, reply);
  });

  // 添加一个测试端点，用于验证CSP报告功能
  fastify.get('/csp-test', async (request, reply) => {
    return {
      message: 'CSP测试端点',
      timestamp: new Date().toISOString(),
      headers: {
        'Content-Security-Policy': request.headers['content-security-policy'],
        'Content-Security-Policy-Report-Only': request.headers['content-security-policy-report-only']
      }
    };
  });
};
